import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://localhost:8085',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API请求错误:', error)
    return Promise.reject(error)
  }
)

// SSE连接函数
export const createSSEConnection = (url, onMessage, onError, onClose) => {
  let isClosed = false
  const eventSource = new EventSource(url)
  
  eventSource.onmessage = (event) => {
    if (!isClosed && onMessage) {
      onMessage(event.data)
    }
  }
  
  eventSource.onerror = (error) => {
    console.error('SSE连接错误:', error)
    if (!isClosed) {
      isClosed = true
      eventSource.close()
      if (onError) {
        onError(error)
      }
    }
  }
  
  eventSource.onopen = () => {
    console.log('SSE连接已建立')
    isClosed = false
  }
  
  // 手动关闭连接的方法
  const close = () => {
    if (!isClosed) {
      isClosed = true
      eventSource.close()
      if (onClose) {
        onClose()
      }
    }
  }
  
  return { eventSource, close, isClosed: () => isClosed }
}

// AI恋爱大师聊天接口
export const chatWithLoveApp = (message, chatId, onMessage, onError, onClose) => {
  const url = `http://localhost:8085/ai/love_app/chat/sse?message=${encodeURIComponent(message)}&chatId=${chatId}`
  return createSSEConnection(url, onMessage, onError, onClose)
}

// AI超级智能体聊天接口
export const chatWithManus = (message, onMessage, onError, onClose) => {
  const url = `http://localhost:8085/ai/manus/chat?message=${encodeURIComponent(message)}`
  return createSSEConnection(url, onMessage, onError, onClose)
}

export default api